package com.wt.struggle.goodbye.main.fragment

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.AudioRecord
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.ProV4Fragment
import com.wt.struggle.goodbye.info.NetInfo
import kotlinx.android.synthetic.main.voice_layout.*
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.view.MotionEvent
import com.example.hd.cuterecorder.CuteRecorder
import com.wt.struggle.goodbye.main.activity.SendTieActivity
import java.util.*


/**
 * 录音
 */
class VoiceFragment : ProV4Fragment() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            8888 -> {
                val endTime = System.currentTimeMillis()
                val indexTime = endTime - startTime
                val mm = indexTime / 1000 / 60
                val ss = indexTime / 1000 % 60
                tvRecordTime.text = ("${mm}分${ss}秒")
            }
        }

    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.voice_layout, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        checkRecord()

        buttonSave.setOnClickListener {

            (activity as SendTieActivity).saveVoice(audioResult)

        }

        imageViewRecordVoice.setOnTouchListener { view, motionEvent ->

            when (motionEvent.action) {

                MotionEvent.ACTION_DOWN -> {

                    if (isGet) {
                        startRecord()
                    } else {
                        checkRecord()
                    }

                    imageViewRecordVoice.setImageBitmap(
                        BitmapFactory.decodeResource(
                            resources,
                            R.drawable.record_voice_samll
                        )
                    )
                }

                MotionEvent.ACTION_UP -> {

                    imageViewRecordVoice.setImageBitmap(
                        BitmapFactory.decodeResource(
                            resources,
                            R.drawable.record_voice
                        )
                    )

                    if (isGet) {

                        val indexTime = stopRecord()

                        val mm = indexTime / 1000 / 60
                        val ss = indexTime / 1000 % 60

                        tvRecordTime.text = ("${mm}分${ss}秒")

                        if (timer != null) {
                            timer!!.cancel()
                        }
                    }

                }
            }
            true
        }
    }

    private var isGet = false

    private fun checkRecord() {

        val code = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.RECORD_AUDIO)
        val code2 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        val code3 = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.READ_EXTERNAL_STORAGE)

        if (code == PackageManager.PERMISSION_GRANTED &&
            code2 == PackageManager.PERMISSION_GRANTED &&
            code3 == PackageManager.PERMISSION_GRANTED
        ) {

            isGet = true

        } else {
            ActivityCompat.requestPermissions(
                activity!!, arrayOf(
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ), 678
            )
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 678) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED &&
                grantResults[2] == PackageManager.PERMISSION_GRANTED
            ) {
                isGet = true
            }
        }
    }


    /**
     * 保存的路径
     */
    private lateinit var fileName: String

    /**
     * 录音完成返回文件
     */
    var audioResult: String = ""


    private var startTime: Long = 0
    private var endTime: Long = 0

    var isRecording = true

    var recorder: CuteRecorder? = null

    /**
     * 开始录音
     */
    private fun startRecord() {

        startTime = System.currentTimeMillis()

        fileName = "${Environment.getExternalStorageDirectory().path}/voice/"


        time()

        recorder = CuteRecorder.Builder()
            .maxTime(60)   //最大录制时间
            .minTime(1)    //最短录制时间
            .outPutDir(fileName)   //输出录音文件路径
            .voiceLevel(CuteRecorder.HIGH)//最大音量
            .build()

        recorder!!.setOnAudioRecordListener(object : CuteRecorder.AudioRecordListener {
            override fun tooShort() {
                showToastShort(activity!!, "录制时间太短")
            }

            override fun finish(p0: Int, p1: String?) {

                audioResult = p1!!

                Log.i("result", "-------$p1")
            }

            override fun curVoice(p0: Int) {
            }

            override fun hasRecord(p0: Int) {
                Log.i("result", "-------" + p0)
            }

        })

        if (recorder != null) {
            if (recorder!!.isPrepared) {
                recorder!!.start();
            }
        }

    }


    /**
     * 定时器
     */
    private var timer: Timer? = null

    private var timerTask: TimerTask? = null

    /**
     * 定时更新时间
     */
    fun time() {

        timer = Timer()

        timerTask = object : TimerTask() {
            override fun run() {
                val message = handler!!.obtainMessage()
                message.what = 8888
                message.obj = ""
                handler!!.sendMessage(message)
            }
        }

        timer!!.schedule(timerTask, 0, 1000)

    }

    /**
     * 停止录音
     */
    private fun stopRecord(): Long {
        endTime = System.currentTimeMillis()

        isRecording = false

        if (recorder != null) {
            recorder!!.stop()
        }

        return endTime - startTime
    }


}